package com.controller;

import com.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
@SessionAttributes(types = {UserBean.class})
public class UserController {

    @RequestMapping("/toReg")
    public String toRegister() {
        return "register.jsp";
    }

    @RequestMapping("/register")
    public String doRegister(@RequestParam("username") String uname,
                             @RequestParam("password") String pwd, Model model) {

        System.out.println("从注册页面传递的用户名=" + uname + " 密码=" + pwd);

        UserBean user=new UserBean();
        user.setUsername(uname);
        user.setPassword(pwd);
        model.addAttribute("user",user);
        return "forward:toLogin";

    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login.jsp";
    }

    @RequestMapping("/doLogin")
    public ModelAndView login(@RequestParam("username") String uname, @RequestParam("password") String pwd,
                              @SessionAttribute("user") UserBean userBean, ModelAndView view) {
        System.out.println("这是通过登录页面传递过来的用户名=" + uname + "密码=" + pwd +
                "****从Session中解析的用户名=" + userBean.getUsername() +
                " 密码=" + userBean.getPassword());

        String msg;
        if (uname.equals(userBean.getUsername()) && pwd.equals(userBean.getPassword())) {
            msg = "登录成功，欢迎进入页面";
        } else {
            msg = "登录失败，用户名或者密码不正确";
        }
        UserBean loginBean = new UserBean();
        loginBean.setUsername(uname);
//        model.addAttribute("msg",msg);
        view.addObject("msg",msg);
        view.addObject("user",loginBean);
        view.setViewName("result.jsp");

//        return "result.jsp";
        return view;

    }

}
